import { DynamicData } from "./dynamic_data";
import { IDynamicPropertyTarget } from "./idynamic_property_target";
import { Logger } from "../utils/debug_log";

export class DynamicJson<T> {
  private static logger: Logger = new Logger(`${DynamicJson.name}`);
  dynamic_data: DynamicData<string>;
  constructor(target: IDynamicPropertyTarget, id: string, value?: T) {
    this.dynamic_data = new DynamicData(
      target,
      id,
      value == undefined ? undefined : JSON.stringify(value)
    );
  }
  get(): T | undefined {
    const raw = this.getRaw();
    if (raw == undefined) return;
    try {
      return JSON.parse(raw);
    } catch {
      DynamicJson.logger.log(`${this.dynamic_data.getId()}:转换值"${raw}"时发生错误`);
      return undefined;
    }
  }
  getRaw() {
    return this.dynamic_data?.get();
  }
  set(value: T): void {
    this.setRaw(JSON.stringify(value));
  }
  setRaw(value: string): void {
    this.dynamic_data?.set(value);
  }
  free(): void {
    this.dynamic_data?.free();
  }
  /**更新数值 */
  update(callback: (arg0: T) => T) {
    const value = this.get();
    if (value != undefined) {
      this.set(callback(value));
    }
  }
}
